package com.app.tool;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class PicUtil {
	@SuppressLint("SdCardPath")
	private static String MYDATABAK_PATH_DIR = "/sdcard/logs/";
	/**
	 * @param 将图片内容解析成字节数组
	 * @param inStream
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception 
	{
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}
	/**
	 * @param 将字节数组转换为ImageView可调用的Bitmap对象
	 * @param bytes
	 * @param opts
	 * @return Bitmap
	 */
	public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) 
	{
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}
	/**
	 * @param 图片缩放
	 * @param bitmap 对象
	 * @param w 要缩放的宽度
	 * @param h 要缩放的高度
	 * @return newBmp 新 Bitmap对象
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h)
	{
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
		return newBmp;
	}
	
	/**
     * 把Bitmap转Byte
     * @Author HEH
     * @EditTime 2010-07-19 上午11:45:56
     */
	public static byte[] Bitmap2Bytes(Bitmap bm){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}
	/**
     * 把字节数组保存为一个文件
     * @Author HEH
     * @EditTime 2010-07-19 上午11:45:56
     */
    public static File getFileFromBytes(byte[] b, String outputFile)
    {
        BufferedOutputStream stream = null;
        File file = null;
        try {
            file = new File(outputFile);
            FileOutputStream fstream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fstream);
            stream.write(b);
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        } 
        finally 
        {
            if (stream != null) {
                try {
                    stream.close();
                } 
                catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return file;
    }
	
    public static void bytesToImageFile(String name, byte[] bytes) 
    {
        try {
            File file = new File(MYDATABAK_PATH_DIR+name+".bmp");
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes, 0, bytes.length);
            fos.flush();
            fos.close();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
    
    /**
     * @方法描述 将RGB字节数组转换成Bitmap，
     */
    static public Bitmap rgb2Bitmap(byte[] data, int width, int height) 
    {
        int[] colors = convertByteToColor(data);    //取RGB值转换为int数组
        if (colors == null) {
            return null;
        }

        Bitmap bmp = Bitmap.createBitmap(colors, 0, width, width, height, Bitmap.Config.ARGB_8888);
        return bmp;
    }


    // 将一个byte数转成int
    // 实现这个函数的目的是为了将byte数当成无符号的变量去转化成int
    public static int convertByteToInt(byte data) 
    {

        int heightBit = (int) ((data >> 4) & 0x0F);
        int lowBit = (int) (0x0F & data);
        return heightBit * 16 + lowBit;
    }


    // 将纯RGB数据数组转化成int像素数组
    public static int[] convertByteToColor(byte[] data) 
    {
        int size = data.length;
        if (size == 0) 
        {
            return null;
        }

        int arg = 0;
        if (size % 3 != 0) 
        {
            arg = 1;
        }

        // 一般RGB字节数组的长度应该是3的倍数，
        // 不排除有特殊情况，多余的RGB数据用黑色0XFF000000填充
        int[] color = new int[size / 3 + arg];
        int red, green, blue;
        int colorLen = color.length;
        if (arg == 0) 
        {
            for (int i = 0; i < colorLen; ++i) 
            {
                red = convertByteToInt(data[i * 3]);
                green = convertByteToInt(data[i * 3 + 1]);
                blue = convertByteToInt(data[i * 3 + 2]);

                // 获取RGB分量值通过按位或生成int的像素值
                color[i] = (red << 16) | (green << 8) | blue | 0xFF000000;
            }
        } 
        else 
        {
            for (int i = 0; i < colorLen - 1; ++i) 
            {
                red = convertByteToInt(data[i * 3]);
                green = convertByteToInt(data[i * 3 + 1]);
                blue = convertByteToInt(data[i * 3 + 2]);
                color[i] = (red << 16) | (green << 8) | blue | 0xFF000000;
            }

            color[colorLen - 1] = 0xFF000000;
        }

        return color;
    }
    
    protected static void writeWord(FileOutputStream stream, int value) throws IOException {  
        byte[] b = new byte[2];  
        b[0] = (byte) (value & 0xff);  
        b[1] = (byte) (value >> 8 & 0xff);  
        stream.write(b);  
    }  
  
    protected static void writeDword(FileOutputStream stream, long value) throws IOException {  
        byte[] b = new byte[4];  
        b[0] = (byte) (value & 0xff);  
        b[1] = (byte) (value >> 8 & 0xff);  
        b[2] = (byte) (value >> 16 & 0xff);  
        b[3] = (byte) (value >> 24 & 0xff);  
        stream.write(b);  
    }  
  
    protected static void writeLong(FileOutputStream stream, long value) throws IOException {  
        byte[] b = new byte[4];  
        b[0] = (byte) (value & 0xff);  
        b[1] = (byte) (value >> 8 & 0xff);  
        b[2] = (byte) (value >> 16 & 0xff);  
        b[3] = (byte) (value >> 24 & 0xff);  
        stream.write(b);  
    }  
    /** 
     * 将Bitmap存为 .bmp格式图片 
     * @param bitmap 
     */  
    @SuppressLint("SdCardPath")
    public static void saveBmp(Bitmap bitmap) {  
        if (bitmap == null)  
            return;  
        // 位图大小  
        int nBmpWidth = bitmap.getWidth();  
        int nBmpHeight = bitmap.getHeight();  
        // 图像数据大小  
        int bufferSize = nBmpHeight * (nBmpWidth * 3 + nBmpWidth % 4);  
        try {  
            // 存储文件名  
            String filename = "/sdcard/logs/id.bmp";  
            File file = new File(filename);  
            if (!file.exists()) {  
                file.createNewFile();  
            }  
            FileOutputStream fileos = new FileOutputStream(filename);  
            // bmp文件头  
            int bfType = 0x4d42;  
            long bfSize = 14 + 40 + bufferSize;  
            int bfReserved1 = 0;  
            int bfReserved2 = 0;  
            long bfOffBits = 14 + 40;  
            // 保存bmp文件头  
            writeWord(fileos, bfType);  
            writeDword(fileos, bfSize);  
            writeWord(fileos, bfReserved1);  
            writeWord(fileos, bfReserved2);  
            writeDword(fileos, bfOffBits);  
            // bmp信息头  
            long biSize = 40L;  
            long biWidth = nBmpWidth;  
            long biHeight = nBmpHeight;  
            int biPlanes = 1;  
            int biBitCount = 24;  
            long biCompression = 0L;  
            long biSizeImage = 0L;  
            long biXpelsPerMeter = 0L;  
            long biYPelsPerMeter = 0L;  
            long biClrUsed = 0L;  
            long biClrImportant = 0L;  
            // 保存bmp信息头  
            writeDword(fileos, biSize);  
            writeLong(fileos, biWidth);  
            writeLong(fileos, biHeight);  
            writeWord(fileos, biPlanes);  
            writeWord(fileos, biBitCount);  
            writeDword(fileos, biCompression);  
            writeDword(fileos, biSizeImage);  
            writeLong(fileos, biXpelsPerMeter);  
            writeLong(fileos, biYPelsPerMeter);  
            writeDword(fileos, biClrUsed);  
            writeDword(fileos, biClrImportant);  
            // 像素扫描  
            byte bmpData[] = new byte[bufferSize];  
            int wWidth = (nBmpWidth * 3 + nBmpWidth % 4);  
            for (int nCol = 0, nRealCol = nBmpHeight - 1; nCol < nBmpHeight; ++nCol, --nRealCol)  
                for (int wRow = 0, wByteIdex = 0; wRow < nBmpWidth; wRow++, wByteIdex += 3) 
                {  
                    int clr = bitmap.getPixel(wRow, nCol);  
                    bmpData[nRealCol * wWidth + wByteIdex] = (byte) Color.blue(clr);  
                    bmpData[nRealCol * wWidth + wByteIdex + 1] = (byte) Color.green(clr);  
                    bmpData[nRealCol * wWidth + wByteIdex + 2] = (byte) Color.red(clr);  
                }  
  
            fileos.write(bmpData);  
            fileos.flush();  
            fileos.close();  
  
        } 
        catch (FileNotFoundException e) 
        {  
            e.printStackTrace();  
        } 
        catch (IOException e) 
        {  
            e.printStackTrace();  
        }  
    }  
    
    public static Bitmap createbmp(byte[] data)//102*126*3
    {   
    	Bitmap bm=rgb2Bitmap(data, 102, 126);    	
    	return bm;
    }
}
